import { GrowlMessageType } from './../components/messageBox/growMeaageType';
import { MessageBoxService } from './../components/messageBox/messageBoxService';
import { Observable } from 'rxjs';
import { ShellWatcher, TaskManage, CardreaderTask, AsyncWatcher } from './../common/LDCManage/taskManage';
import { Injectable } from '@angular/core';
import axios from 'axios';
import * as R from "ramda";

@Injectable()
export class ShellIntegrationService {
    constructor() {
        this.init();
    }

    init(){
        this.start();
    }

    onCardreaderData:(data)=>void

    onScanData:(data)=>void

    start(){
        const scannerGunKeyPressCodes$ = Observable.create((observer, allKeyCodes = [])=>{
            document.addEventListener("keypress",(event)=>{
                allKeyCodes.push(event.keyCode);
                if(event.keyCode == 13){
                    observer.next(allKeyCodes);
                    allKeyCodes = [];
                }
            })
        }).share();
        const scannerGunResult$ = scannerGunKeyPressCodes$.do((keyCodes)=>{
            console.log("scannerGunKeyPressCodes", keyCodes);
        }).map(keyCodes=>keyCodes.slice(0,-1)).map(keyCodes=>keyCodes.map(keyCode=>String.fromCharCode(keyCode)).join("")).share();     
        const serialNo$ = scannerGunResult$.map(result=>(+result).toString().slice(0, -1)).catch((err) => Observable.of(err)).share();

        serialNo$.subscribe(serialNo=>{
            console.log("serialNo",serialNo)
            this.onScanData&&this.onScanData(serialNo);
        })

        const task = new CardreaderTask();
        task.onChecked = (data=>{
            if(task.errorTip[data.retCode]){
                MessageBoxService.current.Growl(GrowlMessageType.Error, task.errorTip[data.retCode]);
            } else {
                 data.data && data.data.uid && (this.onCardreaderData&&this.onCardreaderData(data.data.uid))
            }
        })
    }

    findCardreader(){
        return axios.post("http://localhost:8877"+"/cardReader/read").then(res=>res.data)
    }
}

// cardreader.find("ps/sc","iso1443a",(err,data)=>{console.log(data)})
